#include <stdio.h>
#include <stdlib.h>

#include <SocketUtils.h>
#include <lib/Log/include/Log.h>

int	main(int argc, char **argv)
{
    printf("Hello World\n");

    UdpSocket udp = {0};
    if (createUdpSocketServer(&udp, atoi(argv[1]))) {

        while (1)
        {   
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(0, &fds);
            FD_SET(udp.socket, &fds);

            int ret = select(udp.socket+1, &fds, NULL, NULL, NULL);

            if (ret > 0) {
                if (FD_ISSET(0, &fds)) {
                    char ip[100], buffer[100];
                    int port;
                    scanf("%s %d %s", ip, &port, buffer);

                    UdpSocketOrigin origin = {0};
                    setSocketOriginConnectAddress(&origin, AF_INET, ip, port);
                    udpSocketWrite(&udp, buffer, sizeof(buffer), &origin);
                }

                if (FD_ISSET(udp.socket, &fds)) {
                    char buffer[100];

                    UdpSocketOrigin origin = {0};
                    udpSocketRead(&udp, buffer, sizeof(buffer), &origin);

                    INFO_LOG("[%s:%d]: %s", inet_ntoa(origin.address.sin_addr),
                        ntohs(origin.address.sin_port), buffer);
                }
            }
        }
    }

    return 0;
}
